<template>
  <div class="z-calendar-week">
    <div v-for="(activity, index) in rows" :key="index" class="z-calendar-week__item">
      <div class="z-calendar-week__header">
        <div class="time">
          <span>{{ activity.week }}</span>
          （{{ activity.timestamp | parseTime('{m}月{d}日') }}）
        </div>
        <div class="num">共{{ activity.count }}节课</div>
      </div>
      <div class="z-calendar-week__body">
        <div v-for="(item, i) in activity.list" :key="i" class="z-calendar-week__crad" :class="[{ start: item.live_status == 999, end: item.live_status == 992 }]">
          <div class="time">{{ item.start_time | parseTime('{h}:{i}') }}-{{ item.end_time | parseTime('{h}:{i}') }}</div>
          <div class="title">{{ item.course_title }}</div>
          <div class="salutation">{{ item.sec_title }}</div>
          <div class="name">{{ item.teacher_name }}</div>
          <div v-if="item.live_status == 999 || item.live_status == 992" class="status">{{ item.live_status == 992 ? '已结束' : '直播中' }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/common/js/filters.js';
const validTypes = ['prev', 'today', 'next'];
import { mapState, mapGetters } from 'vuex';
import { range, nextDate } from './date-util';
const getWeekDays = (date, amount) => {
  if (amount <= 0) return [];
  return range(amount).map((_, index) => nextDate(date, index));
};
const getWeekDataDays = (arr1, arr2) => {
  return arr1.reduce((pre, cur) => {
    const target = pre.find(e => e.date === cur.date);
    if (target) {
      Object.assign(target, cur);
    } else {
      pre.push(cur);
    }
    return pre;
  }, arr2);
};

export default {
  props: {
    value: {
      type: [Date, String, Number],
      default: _ => {
        return '';
      }
    },
    title: {
      type: String,
      default: _ => {
        return '';
      }
    },
    teacher: {
      type: String,
      default: _ => {
        return '';
      }
    }
  },
  data() {
    return {
      selectedDay: '',
      now: new Date(),
      list: []
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.info,
      token: state => state.user.token
    }),
    ...mapGetters({
      globThemeColor: 'projectSetting/getGlobThemeColor'
    }),
    prevWeekDatePrefix() {
      const temp = new Date(this.date.getFullYear(), this.date.getMonth(), this.date.getDate() - 7, 1);
      return parseTime(temp, '{y}-{m}-{d}');
    },
    curWeekDatePrefix() {
      return parseTime(this.date, '{y}-{m}-{d}');
    },
    nextWeekDatePrefix() {
      const temp = new Date(this.date.getFullYear(), this.date.getMonth(), this.date.getDate() + 7, 1);
      return parseTime(temp, '{y}-{m}-{d}');
    },
    formatedDate() {
      return parseTime(this.date, '{y}-{m}-{d}');
    },
    formatedToday() {
      return parseTime(this.now, '{y}-{m}-{d}');
    },
    realSelectedDay: {
      get() {
        if (!this.value) return this.selectedDay;
        return this.formatedDate;
      },
      set(val) {
        this.selectedDay = val;
        const date = new Date(val);
        this.$emit('input', date);
      }
    },
    date() {
      return this.toDate(this.value);
    },
    rows() {
      let days = [];
      const date = this.date;
      const dayOfWeek = date.getDay();
      const diff = (dayOfWeek + 7) % 7;
      date.setDate(date.getDate() - diff);
      date.setHours(0, 0, 0, 0);
      const currentWeekDays = getWeekDays(date, 7).map((day, index) => ({
        week: this.weekDays[index],
        date: parseTime(day, '{y}-{m}-{d}'),
        timestamp: day,
        count: 0,
        list: []
      }));
      days = getWeekDataDays(this.list, currentWeekDays);
      return days;
    },
    weekDays() {
      return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    }
  },
  created() {
    this.getData(this.value);
  },
  methods: {
    getData(date) {
      this.list = [];
      this.$http.get(
        '/course/admin/schedule/period',
        { startdate: this.getStartDateOfWeek(date), enddate: this.getEndDateOfWeek(date), title: this.title, teacher: this.teacher },
        res => {
          this.list = res.data.datas;
          this.list.map(item => (item.date = parseTime(item.timestamp, '{y}-{m}-{d}')));
          const sum = this.list.reduce((pre, cur) => {
            return pre + cur.count;
          }, 0);
          // this.list.map(item => (item.date = parseTime(item.start_time, '{y}-{m}-{d} {h}')));
          this.$emit('number', sum);
        }
      );
    },
    pickDay(day) {
      this.realSelectedDay = day;
      this.getData(day);
    },
    selectDate(type) {
      if (validTypes.indexOf(type) === -1) {
        throw new Error(`invalid type ${type}`);
      }
      let day = '';
      if (type === 'prev') {
        day = `${this.prevWeekDatePrefix}`;
      } else if (type === 'next') {
        day = `${this.nextWeekDatePrefix}`;
      } else {
        day = this.formatedToday;
      }
      if (day === this.formatedDate) return;
      this.pickDay(day);
    },
    toDate(val) {
      if (!val) {
        throw new Error('invalid val');
      }
      return val instanceof Date ? val : new Date(val);
    },
    cloneDate(value) {
      return new Date(value.getTime());
    },
    onSearch() {
      this.getData(this.curWeekDatePrefix);
    },
    /**
     * 获取当前周的开始日期
     * @param {string} value Date string
     * @returns {string} 时间戳
     */
    getStartDateOfWeek(value) {
      const date = this.toDate(value);
      /**
       * 星期天为 0
       * 星期一到星期六分别用 1-6 表示
       */
      const dayOfWeek = date.getDay();
      const diff = (dayOfWeek + 7) % 7;
      date.setDate(date.getDate() - diff);
      date.setHours(0, 0, 0, 0);
      return parseTime(date, '{y}-{m}-{d}');
    },
    /**
     * 获取当前周的结束日期
     * @param {string} value Date string
     * @returns {string} 时间戳
     */
    getEndDateOfWeek(value) {
      const date = this.toDate(value);
      /**
       * 星期天为 0
       * 星期一到星期六分别用 1-6 表示
       */
      const dayOfWeek = date.getDay();
      const diff = (dayOfWeek + 7) % 7;
      date.setDate(date.getDate() + (7 - diff - 1));
      date.setHours(0, 0, 0, 0);
      return parseTime(date, '{y}-{m}-{d}');
    }
  }
};
</script>

<style lang="scss" scoped>
$text-color-import: #303133;
$text-color-auxiliary: #909399;
.z-calendar-week {
  display: flex;
  // grid-template-columns: repeat(7, 1fr);
  min-height: 785px;
  margin-bottom: -20px;
  .z-calendar-week__item {
    border-right: 1px solid #ebeef5;
    border-top: 1px solid #ebeef5;
    box-sizing: border-box;
    width: 14.28%;
  }
  .z-calendar-week__header {
    padding: 12px 0;
    background: #f6f7fb;
    border-bottom: 1px solid #ebeef5;
    line-height: 1;
    text-align: center;
    width: 100%;
    .time {
      font-size: 12px;
      color: $text-color-import;
      span {
        font-size: 14px;
        font-weight: 600;
      }
    }
    .num {
      margin-top: 10px;
      font-size: 12px;
      color: $text-color-auxiliary;
    }
  }
  .z-calendar-week__body {
    padding: 15px 5px;
  }
  .z-calendar-week__crad {
    padding: 22px 8px;
    // max-width: 114px;
    margin-bottom: 15px;
    background: #f6f7fb;
    border-radius: 4px;
    line-height: 1;
    position: relative;
    cursor: pointer;
    transition: all 0.2s;
    box-sizing: border-box;
    .time {
      font-size: 14px;
      font-weight: 400;
      color: $text-color-import;
    }
    .title {
      margin-top: 5px;
      font-size: 14px;
      font-weight: 500;
      color: $text-color-import;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .salutation {
      margin-top: 8px;
      font-size: 12px;
      font-weight: 400;
      color: $text-color-auxiliary;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .name {
      margin-top: 15px;
      font-size: 12px;
      font-weight: 400;
      color: $text-color-auxiliary;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .status {
      position: absolute;
      right: 0;
      top: 0;
      padding: 3px 2px;
      font-size: 12px;
      font-weight: 400;
      color: #ffffff;
      border-radius: 0px 4px 0px 4px;
    }
    &.start {
      .status {
        background: #5191ff;
      }
    }
    &.end {
      .time,
      .title {
        color: $text-color-auxiliary;
      }
      .status {
        background: #b7bac1;
      }
    }
    &:hover {
      background: #f0f1f6;
    }
  }
}
</style>
